<!--
 * @Descripttion: GGB
 * @version: 1.0
 * @Author: GGB
 * @Date: 2021-12-11 11:54:01
 * @LastEditors: GGB
 * @LastEditTime: 2021-12-11 12:32:13
-->
<template>
  <li
    :class="{
      completed: todo.completed,
      editing: todo === editedTodo,
    }"
  >
    <div class="view">
      <!-- 绑定完成状态 -->
      <input type="checkbox" v-model="todo.completed" />
      <label @dblclick="editTodo(todo)">{{ todo.title }}</label>
      <button @click="removeTodo(todo)">X</button>
    </div>
    <!-- 编辑待办 -->
    <!-- <input
          type="text"
          class="edit"
          v-todo-focus="todo === editedTodo"
          v-model="todo.title"
          @blur="doneEdit(todo)"
          @keyup.enter="doneEdit(todo)"
          @keyup.escape="cancelEdit(todo)"
        /> -->
    <EditTodo
      class="edit"
      v-todo-focus="todo === editedTodo"
      v-model="todo.title"
      @blur="doneEdit(todo)"
      @keyup.enter.stop="doneEdit(todo)"
      @keyup.escape.stop="cancelEdit(todo)"
    ></EditTodo>
  </li>
</template>

<script>
import { reactive, toRefs } from "vue";
import EditTodo from "./EditTodo.vue";
export default {
  components: {
    EditTodo,
  },
  props: {
    todo: {
      type: Object,
      required: true,
    },
    editedTodo: Object,
  },
  directives: {
    "todo-focus": (el, { value }) => {
      if (value) {
        el.focus();
      }
    },
  },
  emits: ["remove-todo", "update:edited-todo"],
  setup(props, { emit }) {
    const state = reactive({
      beforeEidtCache: "",
    });
    const cancelEdit = todo => {
      todo.title = state.beforeEidtCache;
      //   state.editedTodo = null;
      emit("update:edited-todo", null);
    };
    const editTodo = todo => {
      state.beforeEidtCache = todo.title;
      //   state.editedTodo = todo;
      emit("update:edited-todo", todo);
    };
    const doneEdit = todo => {
      //   state.editedTodo = null;
      emit("update:edited-todo", null);
    };

    const removeTodo = todo => {
      emit("remove-todo", todo);
    };

    return {
      ...toRefs(state),
      cancelEdit,
      editTodo,
      doneEdit,
      removeTodo,
    };
  },
};
</script>

<style scoped>
.completed label {
  text-decoration: line-through;
}
label {
  padding: 5px 10px;
}
.edit,
.editing .view {
  display: none;
}
.view,
.editing .edit {
  display: block;
}
</style>
